function append_message(role, text, avatarUrl) {

  var message_container = $("<div></div>").addClass("message-container");
  var avatar_element = $("<span></span>").addClass("avatar");
  var role_element = $("<p></p>").addClass("role").text(role);

  if (avatarUrl) {
    avatar_element.css("background-image", `url(${avatarUrl})`);
  } else {
    avatar_element.css("background-color", "green"); // Default color if no avatar
  }

  message_container.append(role_element);
  message_container.append(avatar_element);

  var parsedText = role === 'System' ? parseSystemMessage(text) : parseCodeBlocks(text, role);
  message_container.append(parsedText);

  var copyButton = $("<button></button>")
    .addClass("copy-button")
    .text("Copy")
    .click(function () {
      copyToClipboard(parsedText.text()); // Pass text content for copying
      $(this).text("Copied!");
      setTimeout(() => $(this).text("Copy"), 2000);
    });

  message_container.append(copyButton);
  $("#chatMessagesArea").append(message_container); // Append to the new chatMessagesArea
  // Scroll to the bottom of the chatMessagesArea
  var chatArea = document.getElementById('chatMessagesArea');
  if (chatArea) {
    chatArea.scrollTop = chatArea.scrollHeight;
  }
}

function parseCodeBlocks(text, role) {
  var parts = text.split(/(```[\s\S]*?```)/g);
  var parsedText = $("<div></div>").addClass("message-text");
  parts.forEach(part => {
    if (part.startsWith("```") && role != "System") {
      var trimmedBlock = part.trim();
      var languageMatch = trimmedBlock.match(/^```(\w+)?(?:\n|\r)([\s\S]*?)```$/s); // Allow optional language
      var language = languageMatch && languageMatch[1] ? languageMatch[1] : 'plaintext';
      var codeContent = languageMatch && languageMatch[2] ? languageMatch[2] : trimmedBlock.replace(/^```(?:\w+)?(?:\n|\r)?/, '').replace(/```$/, '');
      
      // Use Prism for highlighting
      var highlightedCode = Prism.highlight(codeContent, Prism.languages[language] || Prism.languages.markup, language);
      var codeBlockHTML = `
        <div class="code-block">
          <div class="code-block-header">${role} - ${language}</div>
          <pre class="language-${language} line-numbers"><code>${highlightedCode}</code></pre>
        </div>
      `;
      // Ensure line numbers are applied after adding to DOM if necessary, or use Prism plugin
      parsedText.append(codeBlockHTML);
    } else {
      // Use marked for non-code parts, ensure escaping is handled correctly if text is not pre-escaped
      // For safety, if mixing with jQuery text() or html() methods, ensure consistent escaping
      parsedText.append(marked.parse(part, { breaks: true }));
    }
  });
  // After appending all parts, if Prism line numbers plugin needs re-init for dynamic content:
  // setTimeout(Prism.highlightAll, 0); // Or target specific elements
  return parsedText;
}

function get_new_messages() {
  // Make sure chatMessagesArea exists before trying to count its children
  const chatMessagesArea = document.getElementById('chatMessagesArea');
  if (!chatMessagesArea) return; 

  $.getJSON("/get_messages", function (data) {
    var lastDisplayedMessageIndex = $("#chatMessagesArea .message-container").length;

    for (var i = lastDisplayedMessageIndex; i < data.length; i++) {
      var role = data[i].role;
      var text = data[i].text;
      var avatarUrl = data[i].avatarUrl;
      append_message(role, text, avatarUrl);
    }
    // Apply Prism highlighting to new code blocks if necessary
    // This is often needed for dynamically added content.
    $('#chatMessagesArea pre code').each(function(i, block) {
        Prism.highlightElement(block);
    });
  });
}

function parseSystemMessage(text) {
  var message = $("<div></div>").addClass("message-text").addClass("system-message");
  var lines = text.split('\n');
  var firstLine = lines[0];
  var collapsed = true;

  var messageContent = $("<div></div>").html(marked.parse(firstLine, { breaks: true })).addClass("original-markdown-summary");
  var originalMarkdown = $("<div></div>").html(marked.parse(text, { breaks: true })).addClass("original-markdown-full");

  var expandButton = $("<button></button>")
    .addClass("expand-button")
    .text("Expand")
    .click(function () {
      if (collapsed) {
        messageContent.hide();
        originalMarkdown.show();
        expandButton.text("Collapse");
      } else {
        messageContent.show();
        originalMarkdown.hide();
        expandButton.text("Expand");
      }
      collapsed = !collapsed;
    });

  message.append(messageContent);
  message.append(originalMarkdown);
  message.append(expandButton);

  originalMarkdown.hide();
  return message;
}

function copyToClipboard(textToCopy) {
  var tempTextArea = document.createElement("textarea");
  tempTextArea.value = textToCopy;
  document.body.appendChild(tempTextArea);
  tempTextArea.select();
  document.execCommand("copy");
  document.body.removeChild(tempTextArea);
}

$(document).ready(function () {
  get_new_messages(); // Initial load
  setInterval(function () {
    get_new_messages(); // Poll for new messages
  }, 1000); // Poll every 1 second

  const sendMessageButton = $('#sendMessageButton');
  const roleInput = $('#roleInput');
  const textInput = $('#textInput');
  const taskStatus = $('#taskStatus'); 
  const chatMessagesArea = $('#chatMessagesArea');
  const toggleChatHistoryBtn = $('#toggleChatHistoryBtn');
  const downloadButton = $('#downloadButton');
  const showDocmeeEditorBtn = $('#showDocmeeEditorBtn');
  const generateSuggestionsBtn = $('#generateSuggestionsBtn');
  
  // 全局变量，保存最近一次任务的名称
  let lastTaskNameCreated = null;

  // ----------------------------------------------------------------
  // START: 全新的、独立的聊天记录切换逻辑
  // ----------------------------------------------------------------
  (function() {
    const chatMessagesArea = $('#chatMessagesArea');
    const toggleChatHistoryBtn = $('#toggleChatHistoryBtn');

    if (toggleChatHistoryBtn.length && chatMessagesArea.length) {
      // 关键: 确保此按钮永远不会被意外禁用
      toggleChatHistoryBtn.prop('disabled', false); 

      // 初始化按钮文本
      if (chatMessagesArea.hasClass('hidden')) {
        toggleChatHistoryBtn.text('显示聊天记录');
      } else {
        toggleChatHistoryBtn.text('隐藏聊天记录');
      }

      // 绑定唯一的、独立的点击事件
      toggleChatHistoryBtn.off('click').on('click', function() {
        // 再次确保按钮是可用的，以防万一
        $(this).prop('disabled', false); 

        // 切换聊天区的可见性
        chatMessagesArea.toggleClass('hidden');
        
        // 根据新的状态更新按钮文本
        if (chatMessagesArea.hasClass('hidden')) {
          $(this).text('显示聊天记录');
        } else {
          $(this).text('隐藏聊天记录');
          get_new_messages(); // 当聊天记录区显示时，获取最新消息
        }
      });
    }
  })();
  // ----------------------------------------------------------------
  // END: 全新的、独立的聊天记录切换逻辑
  // ----------------------------------------------------------------
   
  // 查找项目名称（用于下载），从URL参数或最近的响应中获取
  let getTaskName = function() {
    // 优先使用全局变量中保存的任务名称
    if (lastTaskNameCreated) {
      return lastTaskNameCreated;
    }
    
    // 尝试从URL查询参数获取
    const urlParams = new URLSearchParams(window.location.search);
    const taskName = urlParams.get('task_name');
    if (taskName) {
      return taskName;
    }
    
    // 如果URL中没有，尝试从文本输入框获取
    return textInput.val();
  };
  
  // 初始化下载按钮
  function initDownloadButton(taskName) {
    if (downloadButton && taskName) {
      // 先移除之前的点击事件，再添加新的
      downloadButton.off('click').on('click', function(e) {
        e.preventDefault(); // 防止多次点击
        window.location.href = '/download/' + taskName;
      });
      // 确保按钮已启用
      downloadButton.prop('disabled', false);
    }
  }

  // 页面加载时如果已经有任务名，初始化下载按钮
  if (lastTaskNameCreated) {
    initDownloadButton(lastTaskNameCreated);
  }

  // 页面加载时检查是否有任务已完成但界面未更新
  function checkTaskCompletionStatus() {    
    // 只检查最后5条消息，避免检查历史任务消息
    const allMessages = $('#chatMessagesArea .message-container');
    const messageCount = allMessages.length;
    let taskCompleted = false;
    
    // 计算起始索引，只检查最后5条消息
    const startIndex = Math.max(0, messageCount - 5);
    
    // 遍历最后几条消息
    for (let i = startIndex; i < messageCount; i++) {
      const messageElem = allMessages.eq(i);
      const role = messageElem.find('.role').text();
      const text = messageElem.find('.message-text').text();
      
      if (role === 'System' && 
          (text.includes('[Post Info]') || 
           text.includes('任务已成功执行') || 
           text.includes('任务完成') || 
           text.includes('Task completed') || 
           text.includes('任务已完成'))) {
        taskCompleted = true;
        break;
      }
    }
    
    // 如果检测到任务完成，更新UI状态
    if (taskCompleted) {
      if(taskStatus) taskStatus.text('任务执行完毕。');
      sendMessageButton.text('开始生成方案');
      sendMessageButton.prop('disabled', false);
      
      // 启用所有按钮
      if(downloadButton) downloadButton.prop('disabled', false);
      if(showDocmeeEditorBtn) showDocmeeEditorBtn.prop('disabled', false);
      if(generateSuggestionsBtn) generateSuggestionsBtn.prop('disabled', false);
      
      // 获取任务名称并设置下载按钮事件
      const taskName = getTaskName();
      initDownloadButton(taskName);

      // Auto-hide chat history
      if (chatMessagesArea.hasClass('hidden')) {
          chatMessagesArea.removeClass('hidden');
          toggleChatHistoryBtn.text('隐藏聊天记录');
          get_new_messages();
      }
      return true;
    }
    return false;
  }
  
  // 检查当前页面是否正在执行任务
  let isTaskRunning = function() {
    return sendMessageButton.prop('disabled') || 
           sendMessageButton.text().includes('任务发送中') ||
           (taskStatus && taskStatus.text().includes('执行中'));
  };

  // 重置UI到初始状态的辅助函数
  function resetUI() {
    if(taskStatus) taskStatus.text('请在下方输入您的需求和项目名称');
    sendMessageButton.text('开始生成方案');
    sendMessageButton.prop('disabled', false);

    // 重新初始化按钮，以防事件处理器丢失
    initializeSendButton();
    
    // 禁用下载、编辑器和建议按钮，因为没有活动任务
    if(downloadButton) downloadButton.prop('disabled', true);
    if(showDocmeeEditorBtn) showDocmeeEditorBtn.prop('disabled', true);
    if(generateSuggestionsBtn) generateSuggestionsBtn.prop('disabled', true);
  }
  
  // 只有当任务正在运行时才需要检查完成状态
  if (isTaskRunning()) {
    let pageLoadAttempts = 0;
    const maxPageLoadAttempts = 20; // 20次尝试 * 3秒/次 = 1分钟超时
    
    // 定期检查任务状态
    const statusCheckInterval = setInterval(function() {
      pageLoadAttempts++;
      
      // 检查任务是否完成
      const isCompleted = checkTaskCompletionStatus();

      // 如果任务完成，则停止
      if (isCompleted) {
        clearInterval(statusCheckInterval);
        return;
      }
      
      // 如果超时，重置UI
      if (pageLoadAttempts >= maxPageLoadAttempts) {
        clearInterval(statusCheckInterval);
        console.log('页面加载任务检查超时，重置UI。');
        resetUI();
      }
    }, 3000);
  }

  function initializeSendButton() {
    sendMessageButton.off('click').on('click', function () {
      var role = roleInput.val();
      var text = textInput.val();

      if (!role || !text) {
        alert('请填写所有字段。');
        return;
      }

      sendMessageButton.text('任务发送中...');
      sendMessageButton.prop('disabled', true);
      // 禁用事件，防止重复点击
      sendMessageButton.off('click'); 

      if(taskStatus) taskStatus.text('正在发送任务到后端执行...');
      
      // Show chat history when a new task starts, if it was hidden
      $('#chatMessagesArea').removeClass('hidden');
      $('#toggleChatHistoryBtn').text('隐藏聊天记录');

      $.ajax({
        url: '/send_task',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({ role: role, text: text }),
        success: function (response) {
          console.log('任务发送响应:', response);
          if (response.status === 'success') {
            if(taskStatus) taskStatus.text(response.message || '任务已发送，执行中...');
            roleInput.val('');
            textInput.val('');
            
            // 保存创建的任务名称用于下载
            if (response.task_name_created) {
              lastTaskNameCreated = response.task_name_created;
              console.log('保存的任务名称:', lastTaskNameCreated);
            }
            
            // Task to check for completion message from System
            let attempts = 0;
            const maxAttempts = 180; // Max 3 minutes (180 * 1s)
            const checkCompletionInterval = setInterval(function() {
              attempts++;

              if (checkTaskCompletionStatus()) {
                clearInterval(checkCompletionInterval);
                // 任务完成，重新启用按钮
                initializeSendButton();
                return;
              }
              
              if (attempts >= maxAttempts) {
                  clearInterval(checkCompletionInterval);
                  if(taskStatus) taskStatus.text('任务执行超时或未能检测到完成信号。');
                  resetUI();
              }
            }, 1000); // Check every second

          } else {
            if(taskStatus) taskStatus.text(response.message || '任务发送失败。');
            setTimeout(function() {
                  resetUI();
              }, 3000);
          }
        },
        error: function (error) {
          console.error('任务发送失败:', error);
          let errorMsg = '任务发送请求失败。';
          if (error.responseJSON && error.responseJSON.message) {
              errorMsg = error.responseJSON.message;
          } else if (error.responseText) {
              try {
                  const parsedError = JSON.parse(error.responseText);
                  errorMsg = parsedError.message || errorMsg;
              } catch (e) { /* Not JSON */ }
          }
          if(taskStatus) taskStatus.text('错误: ' + errorMsg);
          alert('任务发送失败: ' + errorMsg);
          
          resetUI();
        }
      });
    });
  }

  // 初始化发送按钮
  initializeSendButton();

  // Word导出功能
  $(document).on('click', '.export-word-btn', function() {
    try {
      const suggestionBox = $(this).closest('.suggestion-box');
      if (!suggestionBox.length) {
        console.error('无法找到建议书内容容器。');
        alert('导出失败：无法找到内容。');
        return;
      }

      // 克隆容器以进行处理，避免修改原始DOM
      const contentToExport = suggestionBox.clone();
      
      // 从克隆的容器中移除导出按钮
      contentToExport.find('.export-buttons').remove();
      
      const title = contentToExport.find('h3').text().trim() || '导出内容';
      const filename = `${title}.docx`;

      // 将处理后的HTML内容转换为字符串，并包裹在完整的HTML结构中
      const htmlString = `
        <!DOCTYPE html>
        <html lang="zh-CN">
        <head>
          <meta charset="UTF-8">
          <title>${title}</title>
        </head>
        <body>
          ${contentToExport.html()}
        </body>
        </html>
      `;

      // 使用 html-docx-js 库生成 Blob
      const fileBuffer = htmlDocx.asBlob(htmlString, {
        orientation: 'landscape',
        margins: {
          top: 720, // 1 inch = 720
          bottom: 720,
          left: 720,
          right: 720
        }
      });

      // 创建一个临时的 a 标签来触发下载
      const url = URL.createObjectURL(fileBuffer);
      const a = document.createElement('a');
      a.href = url;
      a.download = filename;
      document.body.appendChild(a);
      a.click();
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 100);

    } catch (error) {
      console.error('导出Word时出错:', error);
      alert('导出失败，请查看浏览器控制台获取更多信息。');
    }
  });

  // 图片导出功能
  $(document).on('click', '.export-img-btn', function() {
    const button = $(this);
    try {
      const suggestionBox = button.closest('.suggestion-box');
      if (!suggestionBox.length) {
        console.error('无法找到建议书内容容器。');
        alert('导出失败：无法找到内容。');
        return;
      }

      const title = suggestionBox.find('h3').text().trim() || '导出内容';
      const filename = `${title}.png`;
      
      // 导出前临时隐藏按钮
      button.parent().hide();

      html2canvas(suggestionBox[0], {
        scale: 2, // 提高分辨率
        useCORS: true // 允许加载跨域图片 (如果需要)
      }).then(canvas => {
        // 导出后重新显示按钮
        button.parent().show();
        
        const image = canvas.toDataURL('image/png', 1.0);
        
        const a = document.createElement('a');
        a.href = image;
        a.download = filename;
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);

      }).catch(error => {
        // 即使出错也要重新显示按钮
        button.parent().show();
        console.error('导出图片时出错:', error);
        alert('导出图片失败，请查看浏览器控制台获取更多信息。');
      });

    } catch (error) {
      // 即使出错也要重新显示按钮
      button.parent().show();
      console.error('导出图片时发生意外错误:', error);
      alert('导出图片失败，请查看浏览器控制台获取更多信息。');
    }
  });
});


